<template>
  <div>
    <vTablePage
    :pageConfig="pageConfig"
    :tableData="tableData"
    :total="total"
    @changeEdit="changeEditType"
    @changePageNo="changePageNo"
    >
    <template #tableHeader>
      <!-- 添加品牌 -->
       <div style="margin-bottom: 5px;">
          <el-button
            type="primary"
            size="default"
            icon="Plus"
            @click="addTradeMark"
          >
          新增品牌
          </el-button>
       </div>
    </template>
    </vTablePage>
    <!-- 修改添加 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
    >
      <el-form
        style="width: 90%"
        :model="trademarkParams"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input
            placeholder="请您输入品牌名称"
            v-model="trademarkParams.tmName"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌Logo" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="cancel">取消</el-button>
        <el-button type="primary" size="default" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
    <!-- 删除 -->
    <el-dialog
      v-model="delDialogVisible"
      title="删除"
      width="500"
    >
      <span>确定删除这条数据吗？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="delDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleClose">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import vTablePage from '../../components/tablePage/index.vue'
import { reqHasTradeMark, reqAddOrUpdateTrademark,
  reqDeleteTrademark } from '@/api/product/trademark'
import type {
  Records,
  TradeMark,
  TradeMarkResponseData,
} from '@/api/product/trademark/type'
import { UploadProps } from 'element-plus/es/components/upload/src/upload'

// 表格配置
const pageConfig = reactive({
  // 是否展示头部
  showHeader: false,
  // 是否展示索引or多选
  showIndex: true,
  showSelection: false,
  // 列表
  columns:[
    {
      label: '品牌名称',
      prop: 'tmName'
    },
    {
      label: '品牌LOGO',
      prop: 'logoUrl',
      isPic: true // 图片
    },
    {
      label: '品牌操作',
      prop: 'operation',
      isEdit: true,
      isFixed: true
    }
  ],
  // 操作列
  editBtns:[
    {
      text: '编辑',
      type: 'edit',
      icon: 'Edit'
    },
    {
      text: '删除',
      type: 'delete',
      icon: 'Delete'
    }
  ]
})
const tableData = ref([])
const total = ref<number>(0)
const pageNo = ref<number>(1)
// 弹框
const dialogFormVisible = ref<boolean>(false)
const delDialogVisible = ref<boolean>(false)
// 表单
let formRef = ref()
let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: ''
})

// 编辑类型
const changeEditType = (val: any) => {
  const { item, row } = val
  if (item.type === 'primary') {
    changeRole(row)
  } else if (item.type === 'edit') {
    changeEdit(row)
  } else if (item.type === 'delete') {
    changeDelete(row)
  }
}
// 编辑
const changeEdit = (row: any) => {
  // console.log(row)
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
  dialogFormVisible.value = true
  Object.assign(trademarkParams, row)

}
// 删除
const uid = ref<number>(0)
const changeDelete = async(row: any) => {
  uid.value = row.id
  delDialogVisible.value = true  
}
// 确定删除
const handleClose = async() => {
  try {
    let res = await reqDeleteTrademark(uid.value)
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '删除品牌成功',
      })
      delDialogVisible.value = false
      //再次获取已有的品牌数据
      getList()
    } else {
      ElMessage({
        type: 'error',
        message: '删除品牌失败',
      })
    }
  } catch (error) {
    console.log(error);
    
  }
}
// 分页
const changePageNo = (row: any) => {
  pageNo.value = row
  getList(pageNo.value)
}
// 添加品牌
const addTradeMark = () => {
  dialogFormVisible.value = true
  trademarkParams.id = 0
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''

  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
}
// 上传图片
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (
    rawFile.type === 'image/png' ||
    rawFile.type === 'image/jpeg' ||
    rawFile.type === 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传的文件大小应小于4M',
      })
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传的文件类型必须是PNG|JPG|GIF',
    })
    return false
  }
}
// 图片成功
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  trademarkParams.logoUrl = response.data
  formRef.value.clearValidate('logoUrl')
}
// 表单校验
const validatorTmName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('品牌名称位数大于等于两位'))
  }
}
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  if (value) {
    callBack()
  } else {
    callBack(new Error('Logo的图片务必上传'))
  }
}
// 清空
const cancel = () => {
  dialogFormVisible.value = false
}
// 提交表单
const confirm = async () => {
  await formRef.value.validate()

  let res = await reqAddOrUpdateTrademark(trademarkParams)
  if (res.code === 200) {
    dialogFormVisible.value = false
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功',
    })
    getList()
  } else {
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? '修改品牌失败' : '添加品牌失败',
    })
  }
}

const rules = {
  tmName: [
    {
      required: true,
      trigger: 'blur',
      validator: validatorTmName,
    },
  ],
  logoUrl: [
    {
      required: true,
      trigger: 'change',
      validator: validatorLogoUrl,
    },
  ],
}
// 获取列表
const getList = async() => {
  const res = await reqHasTradeMark(pageNo.value)
  total.value = res.data.total
  tableData.value = res.data.records
}
onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

</style>